<template>
  <div class="relation-manage">
    <div class="side-bar">
      <b-button
        id="add-node"
        class="btn"
        size="sm"
        :variant="'primary'"
        squared
        @click="openAddRelationModal"
      >
        <i class="el-icon-plus"></i>
        <b-tooltip target="add-node" placement="right">新增关系</b-tooltip>
      </b-button>
      <b-button
        id="del-node"
        class="btn"
        size="sm"
        :variant="'outline-primary'"
        squared
        @click="openDelRelationModal"
      >
        <i class="el-icon-minus"></i>
        <b-tooltip target="del-node" placement="right">删除关系</b-tooltip>
      </b-button>
    </div>
    <!-- main 区域 -->
    <div class="main">
      <div class="condition-wrap flex-left-center">
        <el-form
          :inline="true"
          :model="conditionForm"
          :rules="conditionFormRules"
          ref="conditionForm"
          size="small"
          class="condition-form">
          <el-form-item label="源节点" prop="source">
            <el-select
              v-model="conditionForm.source"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteSearchSourceNodeList"
              :loading="selectLoading"
            >
              <el-option
                v-for="(item, $index) in conditionSourceNodeList"
                :key="$index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="目标节点"
            label-width="100px"
            prop="target"
          >
            <el-select
              v-model="conditionForm.target"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteSearchTargetNodeList"
              :loading="selectLoading"
            >
              <el-option
                v-for="(item, $index) in conditionTargetNodeList"
                :key="$index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="primary"
              style="margin-left: 20px;"
              @click="selectRelationList"
            >查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="relationList.filter(data => !tableSearchKeywords || data.name.toLowerCase().includes(tableSearchKeywords.toLowerCase()))"
        style="width: 100%; padding: 0px 5px"
        :height="tableHeight"
        @selection-change="updateSelectedList"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!-- 关系名称(类型) -->
        <el-table-column prop="name" label="关系名称">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="250">
          <template slot="header" slot-scope="{}">
            <el-input
              filterable
              style="margin: 3px 0px;"
              size="small"
              v-model="tableSearchKeywords"
              placeholder="输入关键字搜索(Enter)"
            />
          </template>
          <template slot-scope="scope">
            <b-button
              style="margin: 3px 0px; text-decoration: none; color: #dc3545"
              size="sm"
              variant="link"
              @click="deleteOne(scope.row.id)"
            >删除</b-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加关系的弹框 -->
    <b-modal
      id="add-relation-modal"
      size="mid"
      no-stacking
      no-close-on-backdrop
      v-model="showAddRelationModal"
    >
      <div class="form">
        <div class="form-line flex-sp-ar">
          <div class="label" style="margin-right: 5px">关系名称</div>
          <div class="form-item">
            <el-select
              style="width: 350px"
              size="small"
              collapse-tags
              v-model="addRelationList"
              multiple
              filterable
              allow-create
              placeholder="关键词(支持创建关系)"
              @focus="remoteSearchRelationTypeList"
              :loading="selectLoading">
              <el-option
                v-for="(item, $index) in searchRelationTypeList"
                :key="$index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <!-- 底部配置 -->
      <template slot="modal-footer">
        <div style="height: 40px; width: 40%" class="flex-right-center">
          <b-button variant="primary" @click="confirmAddRelation" style="font-size: 14px; margin-right: 10px">确定</b-button>
          <b-button variant="outline-danger" @click="showAddRelationModal = false" style="font-size: 14px">取消</b-button>
        </div>
      </template>
      <!-- 头部配置 -->
      <template slot="modal-header">
        <div class="header flex-left-center">新增关系</div>
      </template>
    </b-modal>
  </div>
</template>

<script>
import { getNodeList } from '@/api/node'
import { getRelationList, addRelationList, delRelationList } from '@/api/relation'
import { getRelationTypesV2 } from '@/api/type'
import { getLimitText } from '@/util'

export default {
  data () {
    return {
      // 选中的数据列表
      seletedList: [],
      // 添加的关系列表
      addRelationList: [],
      // 关系下拉列表
      searchRelationTypeList: [],
      // 添加关系列表弹窗控制变量
      showAddRelationModal: false,
      // 全局loading
      loading: false,
      // 表格搜索关键字
      tableSearchKeywords: '',
      selectLoading: false,
      addRelationModal: false,
      // 表格的高度
      tableHeight: window.innerHeight - 130,
      relationList: [],
      // 头部源节点与目标节点选择的表单
      conditionForm: {
        source: '',
        target: ''
      },
      // 节点选择列表
      conditionSourceNodeList: [],
      conditionTargetNodeList: [],
      totalNodeCount: -1,
      // 验证规则
      conditionFormRules: {
        source: [{ required: true, message: '源节点不能为空', trigger: 'blur' }],
        target: [{ required: true, message: '目标节点不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 更新选中的数据列表
    updateSelectedList (rows) {
      this.seletedList = rows
    },
    // 删除一条关系
    deleteOne (id) {
      console.log(id);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id, 'delete id')
        this.loading = this.$loading({
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        delRelationList({ ids: [id] }).then(res => {
          this.loading.close()
          if (res.status === 'fail') {
            this.$message.warning(res.msg)
            return false
          }
          this.$message.success(res.msg)
          this.selectRelationList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 远程搜索关系类型列表下拉框
    remoteSearchRelationTypeList () {
      this.selectLoading = true
      getRelationTypesV2().then(res => {
        this.selectLoading = false
        if (res.status === 'fail') {
          this.$message.warning(res.msg)
          return false
        }
        this.searchRelationTypeList = res.data
      })
    },
    // 确认添加关系
    confirmAddRelation () {
      console.log(this.addRelationList)
      this.loading = this.$loading({
        text: '正在添加...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      addRelationList({
        source: this.conditionForm.source,
        target: this.conditionForm.target,
        relationList: this.addRelationList
      }).then(res => {
        this.loading.close()
        this.showAddRelationModal = false
        if (res.status === 'fail') {
          this.$message.warning(res.msg)
          return false
        }
        this.$message.success(res.msg)
        this.selectRelationList()
      })
    },
    // 查询关系列表
    selectRelationList () {
      this.$refs.conditionForm.validate(v => {
        if (!v) return false
        this.loading = this.$loading({
          text: '正在查询...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        getRelationList(this.conditionForm).then(res => {
          console.log(res, 'relation list')
          this.loading.close()
          if (res.status === 'fail') {
            this.$message.warning(res.msg)
            return false
          }
          this.relationList = res.data
        })
      })
    },
    // 请求节点总个数
    getTotalNodeCount () {
      return new Promise(resolve => {
        getNodeList({
          page: 1,
          records: 1,
          keywords: '',
          type: 'all'
        }).then(res => {
          resolve(res.data.total)
        })
      })
    },
    // 根据关键词查找源节点
    async remoteSearchSourceNodeList (query) {
      if (query === '') {
        this.conditionSourceNodeList = []
        return false
      }
      console.log(query)
      this.selectLoading = true
      if (this.totalNodeCount === -1) {
        this.totalNodeCount = await this.getTotalNodeCount()
      }
      const res = await getNodeList({
        page: 1,
        records: this.totalNodeCount,
        keywords: query,
        type: 'all'
      })
      this.selectLoading = false
      console.log(res)
      if (res.status === 'success') {
        this.conditionSourceNodeList = res.data.nodeList.map(item => {
          return {
            id: item._id, name: `${getLimitText(item.name, 20)}(${item.labels.join(',')})`
          }
        })
      } else {
        this.$message.warning(res.msg)
      }
    },
    // 根据关键词查找目标节点
    async remoteSearchTargetNodeList (query) {
      if (query === '') {
        this.conditionTargetNodeList = []
        return false
      }
      this.selectLoading = true
      if (this.totalNodeCount === -1) {
        this.totalNodeCount = await this.getTotalNodeCount()
      }
      const res = await getNodeList({
        page: 1,
        records: this.totalNodeCount,
        keywords: query,
        type: 'all'
      })
      this.selectLoading = false
      this.conditionTargetNodeList = res.data.nodeList.map(item => {
        return {
          id: item._id, name: `${getLimitText(item.name, 20)}(${item.labels.join(',')})`
        }
      })
    },
    openAddRelationModal () {
      this.$refs.conditionForm.validate(v => {
        if (!v) return false
        this.showAddRelationModal = true
      })
    },
    openDelRelationModal () {
      console.log(this.seletedList)
      this.$confirm('此操作将永久删除已勾选数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = this.$loading({
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        delRelationList({
          ids: this.seletedList.map(item => item.id)
        }).then(res => {
          this.loading.close()
          if (res.status === 'fail') {
            this.$message.warning(res.msg)
            return false
          }
          this.$message.success(res.msg)
          this.selectRelationList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.condition-wrap
  width: 100%
  height: 60px
  .condition-form
    padding: 15px 0px 0px 10px
.relation-manage
  width: 100%
  height: calc(100% - 50px)
  background-color: #fff
  overflow: hidden
  display: flex
.side-bar
  width: 60px
  height: 100%
  box-sizing: border-box
  padding: 20px 0px
  text-align: left
  background-color: #e9ecef
  text-align: center
  .btn
    display: inline-block
    margin-bottom: 20px
    font-size: 18px
.main
  width: calc(100% - 60px)
  height: 100%
  overflow-y: scroll
  &::-webkit-scrollbar
    display: none
</style>
